﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Tb.App.API.Applications.Command.Cultivation;
using Tb.App.Domain.Rabbit.Cultivation;
using Tb.App.ErrorCode;
using Tb.App.Infrastructure.Interfaces;

namespace Tb.App.API.Applications.CommandHandler.Cultivation
{
    /// <summary>
    /// 修改免疫信息-命令
    /// </summary>
    public class UpdImmunityCommandHandler:IRequestHandler<UpdImmunityCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<ImmunityModel> immuityRep;
        private readonly IMapper mapper;

        public UpdImmunityCommandHandler(IBaseRepository<ImmunityModel> immuityRep,
            IMapper mapper)
        {
            this.immuityRep = immuityRep;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(UpdImmunityCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var model=await immuityRep.GetAll().FirstOrDefaultAsync(x=>x.Id==request.Id);
            if (model == null)
            {
                result.Code = ApiEnum.修改失败;
                result.Message = "查询的数据不存在";
            }
            else 
            {
                var ims = mapper.Map(request,model);
                var a = await immuityRep.UpdateAsync(ims);
                if (a > 0)
                {
                    result.Code = ApiEnum.修改成功;
                    result.Message = ApiEnum.修改成功.ToString();
                    result.Data = a;
                }
                else
                {
                    result.Code = ApiEnum.修改失败;
                    result.Message = ApiEnum.修改失败.ToString();
                    result.Data = a;
                }
            }
            
            return result;
        }
    }
}
